package com.luck.easyfoodbatch.custom;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;

import com.luck.easyfoodbatch.callback.JsonCallback;
import com.luck.easyfoodbatch.dialog.CustomAlertDialog;
import com.luck.easyfoodbatch.dialog.SVProgressHUD;
import com.luck.easyfoodbatch.entity.VersionInfo;
import com.luck.easyfoodbatch.util.AppUtils;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.Tools;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/4/6.
 */

public class AutoUpdateManager {
    protected static final String TAG = "MainActivity";
    private Context mContext;
    private SVProgressHUD pd;
    public AutoUpdateManager(Context context) {
        this.mContext = context;
    }

    public void updateVersion() {
        OkHttpUtils.post(HttpUtil.VERSIONUPDATE)
                .tag(this)
                .cacheMode(CacheMode.DEFAULT)
                .cacheKey(TAG)
                .cacheTime(1800)
                .execute(new JsonCallback(mContext, VersionInfo.class) {

                    @Override
                    public void onResponse(boolean isFromCache, Object data, Request request, @Nullable Response response) {
                        VersionInfo versionInfo=(VersionInfo)data;
                        int nowver= AppUtils.getAppInfo(mContext).getVersionCode();
                        if(nowver<versionInfo.getData().getTitle()){
                            showDialogUpdateVersion(versionInfo.getData().getBase_url()+"/"+versionInfo.getData().getDown_url(),versionInfo.getData().getDesc());
                        }
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);

                    }
                });
    }
    /**
     * 是否更新
     */

    private void showDialogUpdateVersion(final String url, String desc) {
        if (Tools.isNull(desc)) {
            desc = "检测到有新版本，是否更新?";
        }
        final CustomAlertDialog dialog = new CustomAlertDialog(mContext).builder();
        dialog.setTitle("发现新版本")
                .setMsg(desc)
                .setCancelable(true)
                .setNegativeButton("暂不更新", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                })
                .setPositiveButton("立即更新", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        downLoadApk(url);
                    }
                }).show();
    }

     /*
        * 从服务器中下载APK
        */


    private void downLoadApk(final String url) {
        pd=new SVProgressHUD(mContext);
        handler.sendEmptyMessage(1);
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = getFileFromServer(url, pd);
                    //pd.dismiss(); // 结束掉进度条对话框
                    handler.sendEmptyMessage(2);
                    InStall(file, mContext);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private File getFileFromServer(String path, SVProgressHUD pd)
            throws Exception {
        // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            // 获取到文件的大小
            //pd.setMax(conn.getContentLength());
            pd.getProgressBar().setMax(conn.getContentLength());
            double fileLength = (double) conn.getContentLength();
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(),
                    path.lastIndexOf("/") + System.currentTimeMillis() + ".apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[4096];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                // 获取当前下载量
                int a = (int) Math.floor((total / fileLength * 100));
                Message message = handler.obtainMessage();
                message.what = 0;
                message.arg1 = a;
                handler.sendMessage(message);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }
    // 安装下载后的apk文件

    private void InStall(File file, Context context) {

        Intent intent = new Intent(Intent.ACTION_VIEW);

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        intent.setAction(Intent.ACTION_VIEW);

        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");

        context.startActivity(intent);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    int a = msg.arg1;
                    pd.getProgressBar().setProgress(a);
                    pd.setText("更新进度 " + a + "%");
                    break;
                case 1:
                    pd.show();
                    pd.showWithStatus("更新进度 0%", SVProgressHUD.SVProgressHUDMaskType.Black);
                    break;
                case 2:
                    if (pd != null && pd.isShowing()) {
                        pd.dismiss();
                    }
                    break;
            }
        }
    };
}
